package com.papper.common.service.base;

import com.papper.common.bean.base.BaseConstFile;
import com.papper.common.bean.base.BaseConstUrl;
import com.papper.common.cache.CacheConstants;
import com.papper.common.cache.redis.CacheClosureNullDefault;
import com.papper.common.mapper.base.BaseConstUrlMapper;
import com.papper.common.service.ServiceImpl;
import com.papper.common.utils.tool.StringTool;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * The type Base const url service.
 *
 * @Author:LaJiao
 * @Date:2022-03-29 10 :06:49
 * @Description:短链接地址库
 */
@Service("baseConstUrlService")
public class BaseConstUrlService extends ServiceImpl<BaseConstUrlMapper, BaseConstUrl> {
    @Override
    protected void clearCaches(BaseConstUrl entity) {
        super.clearCaches(entity);
        cache.delete(CacheConstants.Keys(getModel(), entity.getCode()));
    }

    /**
     * Find by code base const url.
     *
     * @param code the code
     * @return the base const url
     */
    public BaseConstUrl findByCode(final String code) {
        if (StringTool.isEmpty(code)) {
            return null;
        }
        return cache.getAndSet(new CacheClosureNullDefault<BaseConstUrl>() {
            @Override
            public String getKey() {
                return CacheConstants.Keys(getModel(), code);
            }

            @Override
            public BaseConstUrl getValue() {
                Example          example  = new Example(BaseConstFile.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("code", code);
                return findOne(example);
            }

            @Override
            public Class<BaseConstUrl> getTypeReference() {
                return BaseConstUrl.class;
            }
        });
    }

    /**
     * Add info short url.
     *
     * @param code the code
     * @param url  the url
     * @return the short url
     */
    public BaseConstUrl addInfo(String code, String url) {
        BaseConstUrl add = new BaseConstUrl();
        add.setCode(code);
        add.setUrl(url);
        save(add);
        return add;
    }
}
